首先在Controller中新增一個具有HttpPost的Action,判斷式的部分在上次建立的上傳Action中建立一個bool旗標,用來判斷是否上傳成功才能執行下載的動作,file_paths的部分為檔案的完整路徑,為了能夠跨Action接收變數值,這些值都將儲存在全域的static變數當中
上傳的Action
全域static變數
[HttpPost]
public ActionResult Downloads()
{
try
{
//判斷是否有上傳成功
if (log_import_download_flag)
{
FileInfo fl = new FileInfo(file_paths);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fl.Name,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
Response.BufferOutput = false;
var readStream = new FileStream(fl.FullName, FileMode.Open, FileAccess.Read);
string contentType = MimeMapping.GetMimeMapping(fl.FullName);
return File(readStream, contentType);
}
else
{
Response.Write("<script language=javascript>alert('請先匯入檔案');</" + "script>");
return View("ExcelImport");
}
}
catch(Exception ex)
{
Response.Write("<script language=javascript>alert('請先匯入檔案');</" + "script>");
return View("ExcelImport");
}
}
@using (Html.BeginForm("Downloads", "Excel", FormMethod.Post, new { enctype ="multipart/form-data"}))
{
<div class="download_button">
<button class="btn btn-primary" id="download_button">下載檔案</button>
</div>
}